package com.bjbn.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 旅客服务平台Token缓存服务
 *
 * @author bjbn
 */
@Service
public class PspTokenService {

    @Value("${external.psp.token.cache-duration:600}")
    private int cacheDurationSeconds;

    // 使用ConcurrentHashMap存储token和过期时间
    private final ConcurrentHashMap<String, TokenInfo> tokenCache = new ConcurrentHashMap<>();

    /**
     * Token信息类
     */
    private static class TokenInfo {
        private final String token;
        private final LocalDateTime expireTime;

        public TokenInfo(String token, LocalDateTime expireTime) {
            this.token = token;
            this.expireTime = expireTime;
        }

        public String getToken() {
            return token;
        }

        public LocalDateTime getExpireTime() {
            return expireTime;
        }

        public boolean isExpired() {
            return LocalDateTime.now().isAfter(expireTime);
        }
    }

    /**
     * 获取缓存的token
     *
     * @return token，如果不存在或已过期则返回null
     */
    public String getCachedToken() {
        TokenInfo tokenInfo = tokenCache.get("psp_token");
        if (tokenInfo != null && !tokenInfo.isExpired()) {
            return tokenInfo.getToken();
        }
        return null;
    }

    /**
     * 缓存token
     *
     * @param token token字符串
     */
    public void cacheToken(String token) {
        LocalDateTime expireTime = LocalDateTime.now().plusSeconds(cacheDurationSeconds);
        TokenInfo tokenInfo = new TokenInfo(token, expireTime);
        tokenCache.put("psp_token", tokenInfo);
    }

    /**
     * 清除缓存的token
     */
    public void clearToken() {
        tokenCache.remove("psp_token");
    }

    /**
     * 检查token是否存在且未过期
     *
     * @return true表示token有效，false表示token无效或不存在
     */
    public boolean hasValidToken() {
        return getCachedToken() != null;
    }
} 